# -*- coding: utf-8 -*-

import json
import logging

from django.views.decorators.http import require_GET, require_POST

from common.account.db.account import get_account_by_username
from common.platform.metis.handler import get_history
from common.platform.metis.handler import handler as metis_handler
from common.utils import exceptions as err
from common.utils.api import check_params, token_required
from common.utils.decorator import response_wrapper

_LOGGER = logging.getLogger(__name__)

HANDLERS = {
    'metis': metis_handler,
}


@require_POST
@response_wrapper
@token_required
def platform_login(req, platform):
    handler = HANDLERS.get(platform)
    if not handler:
        raise err.ParamError('platform name invalid')
    params = json.loads(req.body)
    game_id = params.get('game_id')
    user_id = req.user_id
    user_name = req.user.user_name
    token = req.user.token
    res = handler.login(user_id, user_name=user_name, game_id=game_id, token=token)
    return {'data': res}


@require_GET
@response_wrapper
@token_required
def platform_logout(req, platform):
    handler = HANDLERS.get(platform)
    if not handler:
        raise err.ParamError('platform name invalid')
    user_id = req.user_id
    res = handler.logout(user_id)
    if not res:
        raise err.ServerError('logout platform error')
    return {'data': res}


@require_GET
@response_wrapper
@token_required
def get_game_history(req):
    params = req.GET.dict()
    page = int(req.GET.get('page', 1))
    size = int(req.GET.get('size', 30))
    user_name = req.GET.get('user_name')

    user_id = req.user_id
    user_ids = [user_id]
    if user_name:
        account = get_account_by_username(user_name)
        if not account:
            raise err.ParamError(u'用户名不存在')
        user_id = account.id
        user_ids = [user_id]
    check_params(params,
                 required_params=['start_date'])
    resp_items = get_history(
        user_ids, params.get('start_date'), params.get('end_date'), page, size)
    ret = dict({'list': resp_items, 'page': page, 'size': len(resp_items)})
    return ret


@require_GET
@response_wrapper
@token_required
def get_game_history(req):
    params = req.GET.dict()
    page = int(req.GET.get('page', 1))
    size = int(req.GET.get('size', 30))

    user_id = req.user_id
    resp_items = get_history(
        user_id, params.get('start_date'), params.get('end_date'), page, size)
    ret = dict({'list': resp_items, 'page': page, 'size': len(resp_items)})
    return ret
